<template>
  <header class="header">
    <div class="header-left">
      <div class="logo">
        <img src="../assets/vue.svg" :alt="t('common.logo')" class="logo-img" />
      </div>
      <h1 class="app-name">{{ t('header.app_name') }}</h1>
    </div>

    <div class="header-right">
      <!-- 语言切换 -->
      <select v-model="currentLocale" @change="changeLocale" class="language-switch">
        <option v-for="lang in languages" :key="lang.value" :value="lang.value">
          {{ lang.label }}
        </option>
      </select>

      <template v-if="isLoggedIn">
        <button class="text-btn" @click="openScenePage">{{ t('header.my_scenes') }}</button>
        <div class="user-info">
          <img :src="userAvatar" :alt="username" class="avatar" />
          <span class="username">{{ username }}</span>
          <button class="text-btn" @click="logout">{{ t('common.logout') }}</button>
        </div>
      </template>
      <template v-else>
        <button class="text-btn" @click="login">{{ t('common.login') }}</button>
      </template>
    </div>
  </header>
</template>

<script>
import { languages } from '../locales'
import axios from 'axios'

export default {
  name: 'Header',
  data() {
    return {
      isLoggedIn: !!localStorage.getItem('token'),
      username: '',
      userAvatar: '',
      languages,
      currentLocale: localStorage.getItem('locale') || 'zh-CN'
    }
  },
  mounted() {
    // Listen to changes in localStorage to update the login state
    window.addEventListener('storage', this.handleStorageChange);

    // If logged in, get user info from localStorage
    if (this.isLoggedIn) {
      const user = JSON.parse(localStorage.getItem('user'));
      if (user) {
        this.username = user.nickName;
        this.userAvatar = user.avatar;
      }
    }
  },
  beforeUnmount() {
    // Remove event listener
    window.removeEventListener('storage', this.handleStorageChange);
  },
  methods: {
    login() {
      // Navigate to login page
      location.href = '/login';
    },
    logout() {
      this.isLoggedIn = false;
      this.username = '';
      this.userAvatar = '';
      localStorage.removeItem('token');
      localStorage.removeItem('user'); // Remove user info from localStorage
      this.$router.push('/login');
    },
    openScenePage() {
      // Open a new tab for the scene page
      window.open('/scene', '_blank');
    },
    async changeLocale() {
      // Save the selected locale in localStorage
      localStorage.setItem('locale', this.currentLocale);
      this.$i18n.locale = this.currentLocale; // Change the language in the app

      // Request backend to switch language
      try {
        const langCode = this.currentLocale.split('-')[0];
        await axios.get(`/api/language/switch?lang=${langCode}`);
      } catch (error) {
        console.error('Failed to switch language on backend:', error);
      }
    },
    t(key) {
      return this.$t(key);
    },
    handleStorageChange(e) {
      // Listen for changes in localStorage (for token and user info)
      if (e.key === 'token') {
        this.isLoggedIn = !!localStorage.getItem('token');
        if (this.isLoggedIn) {
          const user = JSON.parse(localStorage.getItem('user'));
          this.username = user ? (user.nickName ? user.nickName : user.eMail) : '';
          this.userAvatar = user ? user.avatar : '';
        } else {
          this.username = '';
          this.userAvatar = '';
        }
      }
    }
  }
}
</script>


<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-img {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.app-name {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
  margin: 0;
}


.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  margin-right: 15px;
  font-weight: 500;
}

.login-btn,
.logout-btn,
.text-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
  background: none;
  color: #1890ff;
}

.login-btn:hover,
.logout-btn:hover,
.text-btn:hover {
  background-color: #f0f8ff;
  color: #40a9ff;
}

.language-switch {
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}
</style>